[英]Problem with position of html5 shape on canvas with windows scale
[英]HTML5 Canvas Scale position
我第一次試用 canvas,有幾個關於縮放的問題。
在我將 canvas 放大(一半)后,我想設置當前的 position。比例始終將 canvas 設置為 pos 0,0(左上角)。
如果有人知道我如何在縮放時更改 position,請留下答案!
例子
http://i.stack.imgur.com/SLG4v.png原創。
http://i.imgur.com/2nmJZJH.png需要結果。
你可以使用這個例子:
const canvas = document.getElementById("myCanvas"); const ctx = canvas.getContext("2d"); const canvasArea = canvas.width * 2 + canvas.height * 2; const radius = canvasArea * 0.1; const centerX = canvas.width / 2; const centerY = canvas.height / 2; const color = 'blue'; function drawCircle(context, scale, centerX, centerY, radius, color){ context.save() context.beginPath(); context.translate(centerX, centerY); context.scale(scale,scale); context.translate(-centerX,-centerY); context.arc(centerX, centerY, radius, 0, 2 * Math.PI); context.fillStyle = color; context.fill(); context.restore() } function change(el) { canvas.width = canvas.width; canvas.height = canvas.height; const scale = el.value / el.max; drawCircle(ctx, scale, centerX, centerY, radius, color); } change(document.getElementById('rangeInput'));
<canvas id="myCanvas" width="200" height="200" style="border:1px solid #d3d3d3;"> Your browser does not support the HTML canvas tag.</canvas> <br> <input id='rangeInput' type="range" min="0" max="100" value="100" oninput='change(this)' onchange='change(this)' style="width:200px">
獲得您在圖像中顯示的內容。
// ctx is the canvas 2d context
// img is the image
function showImageScaled(img,scale,x,y){
// scale is how big you want it.
// x and y are where in the image you want the top left to be
ctx.setTransform(scale,0,0,scale,0,0);
ctx.drawImage(img,-x,-y); // move the image
}
因此,要查看頂角,放大到兩倍
showImageScaled(img,2,0,0);
在左上角顯示中心,圖像縮放4倍
showImageScaled(img,4,img.width/2,img.height/2);
希望這可以幫助。
Blindman67提供的解決方案的替代方案
您可以使用此精確縮放,以在自定義的中央縮放點縮放圖片(與數碼相機LCD顯示器縮放的方式相同)並進行繪制。
function precisionScale(img,scale,x,y){
/** Function precisionScale
* The function scales the image with a custom central scaling point
* as opposed to 0,0 (top,left) default central scaling point
*/
ctx.translate(x,y);
ctx.scale(scale,scale);
ctx.drawImage(img,-x,-y);
ctx.scale(-scale,-scale);
ctx.translate(-x,-y);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.