html画布变大 影响路径,HTML画布 - 绘图在调整大小时消失

本文探讨了在调整HTML Canvas尺寸时遇到的问题及解决方案。包括重新绘制场景、使用防抖功能减少重绘次数、利用requestAnimationFrame同步刷新率进行平滑缩放等方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

7 个答案:

答案 0 :(得分:19)

调整大小时需要重新绘制场景。

设置画布的宽度或高度,即使将其设置为与之前相同的值,也不仅会清除画布,还会重置整个画布上下文。任何设置属性(fillStyle,lineWidth,裁剪区域等也将被重置。

如果您无法从可能代表画布的任何数据结构中重绘场景,则可以始终通过将整个画布绘制到内存中的画布,设置原始宽度和绘图来保存整个画布。内存中的画布回到原始画布。

这是保存画布位图并在调整大小后将其放回的一个非常快速的示例:

答案 1 :(得分:2)

每次调整画布大小时,它都会将自身重置为透明黑色as defined in the spec。

你要么:

在调整画布大小时重绘,或者,

不要调整画布大小

答案 2 :(得分:0)

当我不得不调整画布的大小以将其调整到屏幕上时,我遇到了同样的问题。

但是我用以下代码解决了它:

var c = document.getElementById('canvas');

ctx = c.getContext('2d');

ctx.fillRect(0,0,20,20);

// Save canvas settings

ctx.save();

// Save canvas context

var dataURL = c.toDataURL('image/jpeg');

// Resize canvas

c.width = 50;

c.height = 50;

// Restore canvas context

var img = document.createElement('img');

img.src = dataURL;

img.οnlοad=function(){

ctx.drawImage(img,20,20);

}

// Restote canvas settings

ctx.restore();

答案 3 :(得分:0)

另一种方法是,如果您担心性能,则可以使用防抖功能。

它不会调整大小或重绘您拖动的每个位置。但是只有在调整大小时,它才会调整大小。

// Assume canvas is in scope

addEventListener.("resize", debouncedResize );

// debounce timeout handle

var debounceTimeoutHandle;

// The debounce time in ms (1/1000th second)

const DEBOUNCE_TIME = 100;

// Resize function

function debouncedResize () {

clearTimeout(debounceTimeoutHandle); // Clears any pending debounce events

// Schedule a canvas resize

debounceTimeoutHandle = setTimeout(resizeCanvas, DEBOUNCE_TIME);

}

// canvas resize function

function resizeCanvas () { ... resize and redraw ... }

答案 4 :(得分:0)

对我有用的一件事是使用requestAnimationFrame()。

let height = window.innerHeight;

let width = window.innerWidth;

function handleWindowResize() {

height = window.innerHeight;

width = window.innerWidth;

}

function render() {

// Draw your fun shapes here

// ...

// Keep this on the bottom

requestAnimationFrame(render);

}

// Canvas being defined at the top of the file.

function init() {

ctx = canvas.getContext("2d");

render();

}

答案 5 :(得分:0)

我有同样的问题。尝试以下代码

var wrapper = document.getElementById("signature-pad");

var canvas = wrapper.querySelector("canvas");

var ratio = Math.max(window.devicePixelRatio || 1, 1);

canvas.width = canvas.offsetWidth * ratio;

canvas.height = canvas.offsetHeight * ratio;

它使图形保持原样

答案 6 :(得分:-1)

我也遇到了这个问题。但是经过实验,我发现调整画布元素大小会自动清除画布上的所有绘图!

只需尝试下面的代码

var canvas1 = document.getElementById('canvas')

console.log('canvas size',canvas1.width, canvas1.height)

var ctx = canvas1.getContext('2d')

ctx.font = 'Bold 48px Arial'

var f = ctx.font

canvas1.width = 480

var f1 = ctx.font

alert(f === f1) //false

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值