簡體   English   中英

如何在Canvas上通過給定坐標繪制圖像?

[英]How to draw image by given coordinate on Canvas?

在此輸入圖像描述

我根據需要嘗試將圖片放在分配的坐標上,但是我可以繪制的形狀和角度都沒有匹配和糾正,只有左上角的匹配

 var _width, _height; var img = new Image(); var img2 = new Image(), img2Widht = 0, img2Height = 0; img.src = "http://production.manboker.com/share/1.jpg"; var canvas = document.getElementById("canvas"); img.onload = function() { canvas.width = _width = this.width; canvas.height = _height = this.height; img2.src = "http://production.manboker.com/share/2.png"; img2.onload = function() { img2Widht = coor['rightTop'][0] - coor['leftTop'][0]; img2Height = coor['leftBottom'][1] - coor['leftTop'][1]; step1(); } } var coor = { leftTop: ["92", "569"], rightTop: ["672", "569"], leftBottom: ["109", "1437"], rightBottom: ["723", "1437"] } var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); function step1() { ctx.clearRect(0, 0, _width, _height); ctx.globalCompositeOperation = 'source-over'; ctx.drawImage(img,0,0); //ctx.globalCompositeOperation = "multiply"; step2(); } function step2() { ctx.drawImage(img2, 92,569,img2Widht,img2Height); } 
 * { padding: 0; margin: 0; } html, body { position: relative; overflow: hidden; height: 100%; width:100%; } 
 <canvas id="canvas" style="position:absolute;"></canvas> 

誰能告訴我如何以正確的角度繪制它?

我將此解決方案作為臨時解決方案發布,如果我能以正確的方式提出旋轉圖像的內容,那么我將其作為新答案發布。

使用上下文的beginPath和lineTo函數,您可以創建一個形狀:

ctx.beginPath();
ctx.lineTo(coor.leftTop[0], coor.leftTop[1]);
ctx.lineTo(coor.rightTop[0], coor.rightTop[1]);
ctx.lineTo(coor.rightBottom[0], coor.rightBottom[1]);
ctx.lineTo(coor.leftBottom[0], coor.leftBottom[1]);
ctx.closePath();

然后,您可以從圖像創建圖案並將其設置為填充樣式

var pattern = ctx.createPatter(img2, "repeat");
ctx.fillStyle = pattern;

然后翻譯上下文,使模式從正確的位置開始(感謝@Kalido fir指出這一點):

ctx.restore();  // set back the context from the previous try
ctx.save();
ctx.translate(coors.leftTop[0], coors.leftTop[1]);

最后,您可以使用該模式填充形狀:

ctx.fill();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM