1.图像放大缩小
<script>
var cvs = document.getElementById("canvas");
cvs.width = 320
cvs.height = 213;
var context = cvs.getContext("2d");
var range = document.getElementById("range");
var img = new Image();
window.onload = function () {
img.src = "imgs/back.jpg";
img.onload = function () {
drawImg(1);
}
}
function drawImg(scale) {
context.clearRect(0, 0, cvs.width, cvs.height);
var w = scale * img.width;
var h = scale * img.height;
var dx = cvs.width / 2 - w / 2;
var dy = cvs.height / 2 - h / 2;
context.drawImage(img, dx, dy, w, h);
}
range.onmousemove = function () {
var v = this.value;
drawImg(v);
}
</script>
<canvas id="canvas"></canvas> <input id="range" type="range" min="0.5" max="3.0" value="1.0" style="600px;" step="0.1" />
上面是通过滑动来放大缩小图像的,在canvas上使用 dragImage(),可以把一张图像绘制到画布上。

drawImage不仅能加载图片,还能加载canvas:

2.对图像加水印
可以在一个画布上加载另一个画布的方法来对图片加水印
<canvas id="canvas"></canvas> <input id="range" type="range" min="0.5" max="3.0" value="1.0" style="600px;" step="0.1" /> <canvas id="canvas1" style="display:none"></canvas>
<script>
var cvs = document.getElementById("canvas");
cvs.width = 600
cvs.height = 600;
var context = cvs.getContext("2d");
var range = document.getElementById("range");
var cvs1 = document.getElementById("canvas1");
cvs1.width = 600;
cvs1.height = 100;
context1 = cvs1.getContext("2d");
var img = new Image();
window.onload = function () {
img.src = "images/1-1.jpg";
img.onload = function () {
drawImg(1);
}
context1.font = "bold 50px Arial";
context1.fillStyle = "rgba(255,255,255,0.5)";
context1.textBaseline = "middle";
context1.fillText("==www.sina.mtn==", 20, 50);
}
function drawImg(scale) {
context.clearRect(0, 0, cvs.width, cvs.height);
var w = scale * img.width;
var h = scale * img.height;
var dx = cvs.width / 2 - w / 2;
var dy = cvs.height / 2 - h / 2;
context.drawImage(img, dx, dy, w, h);
context.drawImage(canvas1, cvs.width - cvs1.width, cvs.height - cvs1.height);
}
range.onmousemove = function () {
var v = this.value;
drawImg(v);
}
</script>
3.图片复制:从画布A得到画布图像,放到画布B上
var dirImg= ctxA.getImageData(0, 0, cvsA.width, cvsA.height);
ctxB.putImageData(dirImg, 0, 0);
putImageData还有四个参数,可以参考下图:
