根据该主题的思路,我想出了一些适合我需要的东西。
事实证明,为了缩放图像以填充图案,您需要2个画布。第一个画布创建在第二个画布中使用的缩放图像。我发现的所有示例都显示了两个画布,但是我只想显示第二个画布
片段:
var c = document.getElementById("DrawQuote");
var ctx = c.getContext("2d");
ctx.clearRect(10, 10, c.width, c.height);
然后ctx上下文用于绘制一些矩形和多边形,我省略了代码
然后我需要绘制一个带有缩放图像图案的矩形
片段:
// create the canvas with scaled image
var imgtoscale = new Image();
imgtoscale.src = "blah.jpg";
var canvas1 = document.getElementById("TempCanvas");
var ctx1 = canvas1.getContext("2d");
canvas1.width = imgtoscale.width / Scale / 4;
canvas1.height = imgtoscale.height / Scale / 4;
ctx1.drawImage(imgtoscale, 0, 0, canvas1.width, canvas1.height);
// draw a rectangle filled with the scaled image from above
// ctx is my main canvas, the one I want to display
ctx.fillStyle = ctx.createPattern(canvas1, "repeat");
ctx.fillRect(400, 40, 300, 300);
显示2张图像:
1-将缩放后的图像缩放到TempCanvas元素
2-具有比例填充图案的矩形到DrawQuote元素
但是我只想显示DrawQuote元素
答案 0 :(得分:1)
不确定您看到的是什么“线程”,但是我想他们只是在显示第二个画布是为了弄清楚发生了什么,但是,您实际上不需要在文档中附加第二个画布,它可以保持“不在屏幕上”。 “:
// the only one visible
var canvas = document.getElementById( 'canvas' );
var ctx = canvas.getContext( '2d' );
var Scale = 2;
var imgtoscale = new Image();
imgtoscale.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/0/04/Woodward_Iowa_Tornado_Damage.JPG/1024px-Woodward_Iowa_Tornado_Damage.JPG";
imgtoscale.onload = function() {
// we create a new canvas element
var canvas1 = document.createElement( 'canvas' );
var ctx1 = canvas1.getContext( '2d' );
canvas1.width = imgtoscale.width / Scale / 4;
canvas1.height = imgtoscale.height / Scale / 4;
ctx1.drawImage( imgtoscale, 0, 0, canvas1.width, canvas1.height );
// draw a rectangle filled with the scaled image from above
// ctx is my main canvas, the one I want to display
ctx.fillStyle = ctx.createPattern( canvas1, 'repeat' );
ctx.fillRect( 100, 100, 300, 300 );
};
canvas { border: 1px solid }
<canvas id="canvas" width="500" height="500"></canvas>
现在请注意,这些线程遗漏的是fillStyle
取决于上下文的当前转换矩阵,因此,您甚至不需要第二个画布即可完成您想要的操作:
首先以正常比例声明要填充的路径,然后将上下文比例设置为所需的比例,最后填充。
// the only canvas
var canvas = document.getElementById( 'canvas' );
var ctx = canvas.getContext( '2d' );
var Scale = 2;
var imgtoscale = new Image();
imgtoscale.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/0/04/Woodward_Iowa_Tornado_Damage.JPG/1024px-Woodward_Iowa_Tornado_Damage.JPG";
imgtoscale.onload = function() {
// create the CanvasPattern directly from the <img>
ctx.fillStyle = ctx.createPattern( imgtoscale, 'repeat' );
// declare your path to fill
ctx.beginPath();
ctx.rect( 100, 100, 300, 300 );
// change the scaling (of the fillStyle)
ctx.scale( 1 / Scale / 4, 1 / Scale / 4 );
ctx.fill();
// reset back to default?
ctx.setTransform( 1, 0, 0, 1, 0, 0 );
};
canvas { border: 1px solid }
<canvas id="canvas" width="500" height="500"></canvas>