首先,我不是专业开发人员,但我正在管理一个有特殊需要的开发项目-使用滑块从中心缩放在HTML5画布上放置的图像。开发人员已经实现了一个滑块,该滑块可以从左上角缩放图像,但是可用性要求从中心调整大小,因此他无法弄清楚。这有可能吗?请在此处查看预装了图片以进行测试的应用的Beta版:

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

单击图像将其选中,然后使用“大小”滑块调整大小。我只是想找出这是否可行,如果可以的话,请向他指出正确的方向。提前谢谢了!

Image slider screenshot

最佳答案

我建议创建一个drawCenteredImage()函数,给它一个图像x,y,宽度,高度,它将以给定的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>

10-04 22:38
查看更多