如果你正在缩放,你必须记住,你用来定位的坐标也会被放大,所以如果你缩放了4,那么你的坐标将是200 * 4而不是@987654324 @。要单独缩放图像,您可以使用调用 drawImage(img,x,y,width,height) 并使用...
var c = document.getElementById("mycanvas");
var ctx = c.getContext("2d");
var scale = 4;
var width = img.width * scale;
var height = img.height * scale;
ctx.drawImage(img, 0, 0, width, height);
ctx.drawImage(img, 200, 200, width, height);
或者您需要将坐标除以比例因子...
var c = document.getElementById("mycanvas");
var ctx = c.getContext("2d");
var scale = 4;
ctx.scale(scale, scale);
ctx.drawImage(img, 0, 0);
ctx.drawImage(img, 200 / scale, 200 / scale);
我整理了一个小提琴,展示了后一种方法,使用剪切来确保图像保持在其象限http://jsfiddle.net/ujtd2/
编辑使用状态堆栈可以避免必须自己进行转换。
var c = document.getElementById("mycanvas");
var ctx = c.getContext("2d");
var scale = 4;
// add a new item to the context state stack
ctx.save();
ctx.scale(scale, scale);
ctx.drawImage(img, 0, 0);
// discard the previous state be restoring the last state
// back to normal scale
ctx.restore();
// Set translation
ctx.translate(200, 200);
// Repeat for second image
ctx.save();
ctx.scale(scale, scale);
ctx.drawImage(img, 0, 0);
我现在跟着。要从特定坐标放大并显示场景的一部分,请使用 translate。
ctx.scale(4, 4);
ctx.translate(-200, -200);
ctx.drawImage(img, 0, 0);
ctx.drawImage(img, 200, 200);
这会放大 4 倍,然后通过将绘图坐标向上和向左平移 200 像素,将可见部分向下和向右移动 200 像素。