You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Canvas中加载的图片成为静态不可编辑背景(jQuery dRawr)

解决方案:双层Canvas实现静态背景+可编辑绘制层

核心问题是背景图和用户绘制内容在同一个Canvas上,导致擦除、清绘操作会同时修改背景。通过双层Canvas分离背景与绘制层,就能实现背景静态不可编辑、仅用户绘制内容可修改的需求。

步骤1:修改HTML结构,添加背景Canvas

在容器内新增一个底层Canvas专门承载背景图,与原绘制Canvas重叠放置:

<div id="drawr-container" style="margin:20px;width:450px;height:450px;border:2px dotted gray;position:relative;" img-src="<?php echo $response; ?>">
    <!-- 背景Canvas:下层,仅显示静态图,不可交互 -->
    <canvas id="bg-canvas-<?php echo $modQuestions->section_num; ?>" class="bg-canvas" style="position:absolute;top:0;left:0;"></canvas>
    <!-- 用户绘制Canvas:上层,负责所有绘制作答操作 -->
    <canvas id="canvas-<?php echo $modQuestions->section_num; ?>" class="question-canvas drawr-canvas" style="position:absolute;top:0;left:0;"></canvas>
</div>
  • 容器需设置position:relative,保证两个Canvas能在容器内绝对定位重叠。
  • 背景Canvas默认不可交互,无需绑定任何绘制事件。

步骤2:调整JS逻辑,分离背景与绘制层

移除原代码中把背景图加载到绘制Canvas的逻辑,将背景图单独绘制到底层Canvas,上层仅初始化drawr插件处理用户绘制:

$(document).ready(function() {
    if($(".question-canvas").length) {
        $(".question-canvas").each(function(index) {
            const $drawCanvas = $(this);
            const $container = $drawCanvas.parent();
            const bgCanvasId = $drawCanvas.attr('id').replace('canvas-', 'bg-canvas-');
            const $bgCanvas = $('#' + bgCanvasId);
            const imgSrc = $container.attr("img-src");
            const canvasWidth = 800;
            const canvasHeight = 600;

            // 统一设置两个Canvas的尺寸,避免错位
            $drawCanvas.attr({width: canvasWidth, height: canvasHeight});
            $bgCanvas.attr({width: canvasWidth, height: canvasHeight});

            // 绘制静态背景到底层Canvas
            if(imgSrc) {
                const bgCtx = $bgCanvas[0].getContext('2d');
                const img = new Image();
                img.onload = function() {
                    bgCtx.drawImage(img, 0, 0, canvasWidth, canvasHeight);
                }
                img.src = imgSrc;
            }

            // 初始化上层绘制Canvas的drawr插件
            $drawCanvas.drawr({
                "enable_transparency" : false,
                "canvas_width" : canvasWidth,
                "canvas_height" : canvasHeight
            });
            $drawCanvas.drawr("start");
        });
    }
});

关键说明

  1. 分层隔离:背景图仅存在于底层Canvas,用户的绘制、擦除、清绘操作仅作用于上层Canvas,完全不会影响背景。
  2. 移除冗余代码:删掉原代码中$drawCanvas.drawr("load", imgSrc)的调用,该方法会把背景图加载到绘制Canvas中,导致背景与绘制内容混淆。
  3. 尺寸对齐:确保两个Canvas的宽高完全一致,避免背景与绘制区域错位。

内容的提问来源于stack exchange,提问作者Dylano236

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 16:05:21