19

如何在不工作的情况下更改putImageData比例scale(1.5, 1.5)..

var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
context.clearRect(0, 0, canvas.width, canvas.height);
context.scale(1.5, 1.5);
context.putImageData(imageData, 0, 0);
4

1 回答 1

27

正确,您的代码不会缩放现有图纸。

context.scale只影响新图纸,不影响现有图纸。

context.putImageData会将保存的原始像素放回画布上,但 putImageData 不是绘图命令,因此其结果不会被缩放。

要缩放现有像素,您必须将像素保存到画布外部的实体中。外部实体可以是新的 Image 元素或第二个 Canvas 元素。

示例代码和演示:http: //jsfiddle.net/m1erickson/p5nEE/

// canvas related variables
var canvas=document.getElementById("canvas");
var context=canvas.getContext("2d");

// draw a test square
context.fillStyle="red";
context.fillRect(0,0,50,50);

// create an image from the canvas
// clear & scale the canvas
// draw the image to the canvas
var imageObject=new Image();
imageObject.onload=function(){

    context.clearRect(0,0,canvas.width,canvas.height);
    context.scale(1.2,1.2);
    context.drawImage(imageObject,0,0);
  
}
imageObject.src=canvas.toDataURL();
于 2014-06-28T16:33:29.503 回答