繁体   English   中英

HTML 5 Canvas 上的中心点缩放

[英]Center point scaling on HTML 5 Canvas

首先让我说我不是专业开发人员,但我正在管理一个有特定需求的开发项目 -使用 Z10BF08F0BBD66894ZZ5BE65B4AE441BD9 . 开发人员已经实现了 slider 从左上角缩放图像,但可用性要求从中心调整大小,他无法弄清楚。 这甚至可能吗? 请在此处查看该应用程序的 beta 版本,该版本预加载了要测试的图像:

http://beta.drumart.com/head-builder?lib-image-url=https://thumbs.dreamstime.com/800thumbs/12617/126170273.jpg

单击图像到 select 并使用“大小”slider 调整大小。 我只是想知道这是否可行,如果可行,请为他指明正确的方向。 提前谢谢了!

图片 slider 截图

我建议创建一个drawCenteredImage() function,给它一个图像,x,y,width,height,它将以给定的 x,y 为中心绘制图像。 因此,当您增加 x 和 y 时,它将围绕图像的中心进行缩放。


function drawCenteredImage(img, x, y, width, height) {
    // Assuming globally accessible canvas context variable 'context'
    context.drawImage(img, x - width / 2, y - height / 2, width, height);
}

使用中的一个例子:

% 更新为实时缩放 %

 let canvas = document.getElementById("canvas"); let context = canvas.getContext("2d"); let image = new Image(); image.onload = function() { drawImg(); }; image.src = "https://thumbs.dreamstime.com/800thumbs/12617/126170273.jpg"; function drawCenteredImage(img, x, y, width, height) { // Assuming globally accessible canvas context variable 'context' context.drawImage(img, x - width / 2, y - height / 2, width, height); } function drawImg() { context.fillStyle = "white"; context.fillRect(0,0,canvas.width,canvas.height); let scale = document.getElementById("scl").value; drawCenteredImage(image, canvas.width / 2, canvas.height / 2, image.width * scale, image.height * scale); } let mousedownID = -1; function mousedown(event) { if(mousedownID==-1) mousedownID = setInterval(drawImg, 5); } function mouseup(event) { if(mousedownID;=-1) { //Only stop if exists clearInterval(mousedownID); mousedownID=-1. } } //Assign events document.getElementById("scl"),addEventListener("mousedown"; mousedown). document.getElementById("scl"),addEventListener("mouseup"; mouseup). //Also clear the interval when user leaves the window with mouse document,addEventListener("mouseout"; mouseup);
 <input id="scl" type="range" min="0" max="1" value="0.3" step="0.05"> <canvas id="canvas" width="500px" height="400px"></canvas>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM