我有240x157 png,和div大小为120x88
所以,我制作了240x157的画布并粘贴png。
div的大小比png小,但是div有滚动条,我可以用拖拽条看到整个图片。这是完美的。
var ctx = $('canvas')[0].getContext('2d');
console.log("test")
var chara = new Image();
chara.src = "https://dl.dropbox.com/s/yr8ehzbdwm0csc7/Madeira_-_Entrance_to_Town%2C_c._1900.jpg?dl=0";
chara.onload = () => {
ctx.clearRect(0, 0,240,157);
ctx.drawImage(chara,0,0,240,157);
}
#whole{
border:1px solid;
width:120px;
height:78px;
overflow:scroll;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="whole"> <canvas id="test" width="240px" height="157px"></canvas> </div>
我的最终目标是通过用户改变比例,当图片大于div时,会出现滚动条,如photoshop等。
所以,我测试了1/2的比例,看到整个图片在129 x78
看起来成功了,但是仍然有滚动条,它没有滚动必要的区域。
为什么会这样呢?
在我的理解中,当画布尺寸为240x157,比例为1/2时,应该出现120x78,为什么只有图片收缩而不是画布本身?
var ctx = $('canvas')[0].getContext('2d');
console.log("test")
var chara = new Image();
chara.src = "https://dl.dropbox.com/s/yr8ehzbdwm0csc7/Madeira_-_Entrance_to_Town%2C_c._1900.jpg?dl=0";
ctx.scale(1/2,1/2) // adding here.
chara.onload = () => {
ctx.clearRect(0, 0,240,157);
ctx.drawImage(chara,0,0,240,157);
}
#whole{
border:1px solid;
width:120px;
height:78px;
overflow:scroll;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="whole"> <canvas id="test" width="240px" height="157px"></canvas> </div>
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
你忘了改变画布的大小并设置overflow:auto,这样滚动条就会消失:
const canvas = $('canvas')[0]; var ctx = canvas.getContext('2d'); console.log("test") var chara = new Image(); chara.src = "https://dl.dropbox.com/s/yr8ehzbdwm0csc7/Madeira_-_Entrance_to_Town%2C_c._1900.jpg?dl=0"; $zoom.addEventListener('input', () =>{ const zoom = $zoom.value * .5; canvas.width = 240 * zoom; canvas.height = 157 * zoom; ctx.scale(zoom,zoom) // adding here. ctx.clearRect(0, 0,240,157); ctx.drawImage(chara,0,0,240,157); }); chara.onload = () => { ctx.clearRect(0, 0,240,157); ctx.drawImage(chara,0,0,240,157); }#whole{ border:1px solid; width:120px; height:78px; overflow:auto; } canvas{ margin:0; display:block; }