绘制文本
window.onload = function () {
var canvas = document.querySelector('#test')
if (canvas.getContext) {
var ctx = canvas.getContext("2d")
ctx.font = "60px impact"
ctx.textBaseline = 'middle'
var w = ctx.measureText('绘制文本').width
ctx.fillText('绘制文本', (canvas.width - w) / 2, (canvas.height - 60) / 2)
}
}
渐变
window.onload = function () {
var canvas = document.querySelector('#test')
if (canvas.getContext) {
var ctx = canvas.getContext("2d")
var gradient = ctx.createRadialGradient(200, 200, 80, 200, 200, 160)
gradient.addColorStop(0, "red")
gradient.addColorStop(0.5, "yellow")
gradient.addColorStop(1, "blue")
ctx.fillStyle = gradient
ctx.fillRect(0, 0, 400, 400)
}
}
使用图片
window.onload = function() {
var canvas = document.querySelector('#test')
if (canvas.getContext) {
var ctx = canvas.getContext("2d")
ctx.translate(70, 100)
var img = new Image()
img.src = "test.png"
img.onload = function() {
draw()
}
function draw() {
var pattern = ctx.createPattern(img, "no-repeat")
ctx.fillStyle = pattern
ctx.fillRect(0, 0, img.width, img.height)
}
}
}
像素操作(实现马赛克)
window.onload = function () {
var canvas = document.querySelector('#test')
if (canvas.getContext) {
var ctx = canvas.getContext("2d")
var img = new Image()
img.src = "test.png"
img.onload = function () {
canvas.width = img.width * 2
canvas.height = img.height
draw()
}
function draw() {
ctx.drawImage(img, 0, 0)
var oldImgdata = ctx.getImageData(0, 0, img.width, img.height)
var newImgdata = ctx.createImageData(img.width, img.height)
var size = 4
for (var i = 0; i < oldImgdata.width / size; i++) {
for (var j = 0; j < oldImgdata.height / size; j++) {
var color = getPxInfo(oldImgdata, i * size + Math.floor(Math.random() * size), j * size +
Math.floor(Math.random() * size))
for (var a = 0; a < size; a++) {
for (var b = 0; b < size; b++) {
setPxInfo(newImgdata, i * size + a, j * size + b, color)
}
}
}
}
ctx.putImageData(newImgdata, img.width, 0);
}
function getPxInfo(imgdata, x, y) {
var color = []
var data = imgdata.data
var w = imgdata.width
color[0] = data[(y * w + x) * 4]
color[1] = data[(y * w + x) * 4 + 1]
color[2] = data[(y * w + x) * 4 + 2]
color[3] = data[(y * w + x) * 4 + 3]
return color
}
function setPxInfo(imgdata, x, y, color) {
var data = imgdata.data
var w = imgdata.width
data[(y * w + x) * 4] = color[0];
data[(y * w + x) * 4 + 1] = color[1];
data[(y * w + x) * 4 + 2] = color[2];
data[(y * w + x) * 4 + 3] = color[3];
}
}
}
合成与裁剪
- 全局透明度的设置:ctx.globalAlpha = value;
- globalCompositeOperation
- source:新的图像(源)
- destination:已经绘制过的图形(目标)
- ctx.globalCompositeOperation = type;
- type:
1.source-over:源在上面/destination-over:目标在上面
2.source-in:重叠中源的部分/destination-in:重叠中目标的部分
3.source-out:源超过目标的部分/destination-out:目标超过源的部分
4.source-atop:砍掉源溢出的部分/destination-atop:砍掉目标溢出的部分