我正在尝试使<canvas>
缩放(放大,缩小)。
我正在尝试使用以下代码来处理缩放功能,但是,它无法按预期工作,因为只要我尝试放大/缩小,画布就会变空/空白。
这让我相信mousewheel
函数正在运行,但是因为它“删除”了画布图,所以它已经关闭了。
function drawZoom() {
var startScale = 1;
var scale = startScale;
var floor = $("#floorplan")[0].getContext("2d")
var width = floor.canvas.width;
var height = floor.canvas.height;
var intervalId;
var imageData = floor.getImageData(0, 0, width, height);
var canvas = $("<canvas>").attr("width", width).attr("height", height)[0];
canvas.getContext("2d").putImageData(imageData, 0, 0);
function drawContents(){
var newWidth = width * scale;
var newHeight = height * scale;
floor.save();
floor.translate(-((newWidth-width)/2), -((newHeight-height)/2));
floor.scale(scale, scale);
floor.clearRect(0, 0, width, height);
floor.drawImage(canvas, 0, 0);
floor.restore();
}
$("#test").on('DOMMouseScroll mousewheel',function(e) {
var e = e || window.event; // old IE support
var theEvent = e.originalEvent.wheelDelta || e.originalEvent.detail*-1;
if(theEvent / 120 > 0) {
zoomin();
} else {
zoomout();
}
if (e.preventDefault)
e.preventDefault();
});
function zoomin()
{
scale = scale + 0.01;
drawContents();
}
function zoomout()
{
scale = scale - 0.01;
drawContents();
}
}
我在这里做错了什么?我该如何解决这个问题?
答案 0 :(得分:0)
我可以在你的drawSettings中添加wheel hanlder,如下所示:
//Drag settings start
function drawSettings() {
//snip....
if (canvas.addEventListener) {
// IE9, Chrome, Safari, Opera
canvas.addEventListener("mousewheel", MouseWheelHandler, false);
// Firefox
canvas.addEventListener("DOMMouseScroll", MouseWheelHandler, false);
}
// IE 6/7/8
else canvas.attachEvent("onmousewheel", MouseWheelHandler);
//其余代码......
需要使用delta值为您的示例定制放大和缩小功能。添加我从这里找到的这个函数:https://www.sitepoint.com/html5-javascript-mouse-wheel/并根据需要改变画布大小。
function MouseWheelHandler(e) {
// cross-browser wheel delta
var e = window.event || e; // old IE support
var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
canvas.style.width = Math.max(50, Math.min(800, canvas.width + (30 * delta))) + "px";
canvas.style.height = Math.max(50, Math.min(800, canvas.width + (30 * delta))) + "px";
return false;
}