HTML 5 Canvas 似乎重绘了删除的部分

2023-08-02前端开发问题
5

本文介绍了HTML 5 Canvas 似乎重绘了删除的部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我在 jsfiddle 上创建了以下代码.目标是在单击后从画布中删除一个框.实际发生的是网格被清除并完全重新绘制,并在其旧位置删除了框.只有当所有给定的对象都被删除时,网格才会显示为空......我很困惑!我做错了什么?

I have created the following code on jsfiddle. The goal is to remove a box from the canvas after it has been clicked. What actually happens is that the grid is cleared and completely redrawn WITH the removed box in it's old spot. The grid will only appear empty when all of the given objects have been removed... I am puzzled! What am I doing wrong?

jQuery(function(){

    GridBox = new GridBox();

    GridBox.init();

    var canvas    = GridBox.canvas;

    canvas.on( 'click', GridBox.clickHandler );

});

function GridBox()
{

    this.target        = { x: 0, y: 0 };
    this.current       = { x: 0, y: 0 };
    this.boxHeight     = 50;
    this.boxWidth      = 50;
    this.width         = 500;
    this.height        = 500;
    this.context       = null;
    this.canvas        = null;

    var self = this,
        init = false,
        bw   = this.width,
        bh   = this.height,
        p    = 0,
        cw   = bw + ( p * 2 ) + 1,
        ch   = bh + ( p * 2 ) + 1;

    /**
     * Array of boxes that are painted on the grid.
     * Each box has its own x and y coordinates.
     */
    this.boxesOnGrid    = [
        { x: 2, y: 2 },
        { x: 9, y: 2 },
        { x: 5, y: 5 }
    ];

    /**
     * Initiate this object
     * @constructor 
     */
    this.init    = function()
    {
        if( !init ) {
            var canvas    = jQuery( '<canvas/>' ).attr({ width: cw, height: ch }).appendTo( 'body' );

            this.canvas     = canvas;
            this.context    = this.canvas.get( 0 ).getContext( '2d' );

            this.createGrid();

            init    = true;

        }
    };

    this.clearGrid        = function()
    {
        alert( 'clearing grid' );
        this.context.clearRect( 0, 0, 500, 500 );
    };

    /**
     * Create the grid 
     */
    this.createGrid        = function()
    {
        for( var x = 0; x <= bw; x += this.boxWidth ) {
            this.context.moveTo( 0.5 + x + p, p );
            this.context.lineTo( 0.5 + x + p, bh + p );
        }

        for( var x = 0; x <= bh; x += this.boxHeight ) {
            this.context.moveTo( p, 0.5 + x + p );
            this.context.lineTo( bw + p, 0.5 + x + p );
        }

        this.context.strokeStyle    = "#aaa";
        this.context.stroke();

        var boxes    = this.boxesOnGrid;

        this.boxesOnGrid    = [];

        for( key in boxes ) {
            var currentBox    = boxes[ key ];
            alert( 'i want to create box ' + currentBox.x + 'x' + currentBox.y );
            this.createBoxAt( currentBox.x, currentBox.y );
        }
    };

    /**
     * Find a suitable path between two boxes
     */
    this.findPath        = function()
    {

    };

    this.clickHandler    = function( event )
    {
        var clickOffset        = {
                x:    event.offsetX,
                y:    event.offsetY
            }, clickedBox    = {
                x:    Math.ceil( clickOffset.x / 50 ),
                y:    Math.ceil( clickOffset.y / 50 )
            };

        for( key in GridBox.boxesOnGrid ) {
            if( GridBox.boxesOnGrid[ key ].x === clickedBox.x && GridBox.boxesOnGrid[ key ].y === clickedBox.y ) {
                GridBox.clearGrid();
                GridBox.removeBox( key );
                GridBox.createGrid();
            }
        }

    };

    /**
     * Remove a box from the grid by removing it from the boxes array
     * and re-drawing the grid.
     */
    this.removeBox        = function( key )
    {
        alert( 'removing box ' + key );
        this.boxesOnGrid.splice( key, 1 );
    };

    /**
     * Create a box at a given coordinate on the grid
     * @param    {int} x
     * @param    {int} y 
     */
    this.createBoxAt    = function( x, y )
    {
        var box    = {
                x:    x * this.boxWidth - this.boxWidth,
                y:    y * this.boxHeight - this.boxHeight
            };

        this.createBox( box.x, box.y );
        this.saveBox( x, y );
    };

    this.createBox    = function( xpos, ypos )
    {
        this.context.rect( xpos, ypos, this.boxWidth, this.boxHeight );
        this.context.fillStyle    = '#444';
        this.context.fill();
    };

    this.saveBox    = function( x, y )
    {
        this.boxesOnGrid.push( { x: x, y: y } );
    };
}

推荐答案

工作小提琴

createBox 更改为以下内容.

Change createBox to the following.

  this.createBox    = function( xpos, ypos )
    {
        this.context.beginPath();
        this.context.rect( xpos, ypos, this.boxWidth, this.boxHeight );
        this.context.fillStyle    = '#444';
        this.context.fill();
        this.context.closePath();
    };

您没有正确开始/结束路径,因此在重绘时不会清除先前的路径,从而再次将它们全部填充.另一种解决方法是改用 fillRect.

Your not properly starting/ending paths, so the previous path isnt cleared when you redraw thus filling them all in again. Another way around it is to just use fillRect instead.

创建路径的第一步是调用 beginPath 方法.在内部,路径存储为子路径(线、弧等)的列表,它们一起形成一个形状.每次调用此方法时,列表都会重置,我们可以开始绘制新形状.

The first step to create a path is calling the beginPath method. Internally, paths are stored as a list of sub-paths (lines, arcs, etc) which together form a shape. Every time this method is called, the list is reset and we can start drawing new shapes.

进一步阅读

这篇关于HTML 5 Canvas 似乎重绘了删除的部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

js删除数组中指定元素的5种方法
在JavaScript中,我们有多种方法可以删除数组中的指定元素。以下给出了5种常见的方法并提供了相应的代码示例: 1.使用splice()方法: let array = [0, 1, 2, 3, 4, 5];let index = array.indexOf(2);if (index -1) { array.splice(index, 1);}// array = [0,...
2024-11-22 前端开发问题
182

layui中表单会自动刷新的问题
layui中表单会自动刷新的问题,因为用到layui的表单,遇到了刷新的问题所以记录一下: script layui.use(['jquery','form','layer'], function(){ var $ = layui.jquery, layer=layui.layer, form = layui.form; form.on('submit(tijiao)', function(data){ a...
2024-10-23 前端开发问题
262

JavaScript小数运算出现多位的解决办法
在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会...
2024-10-18 前端开发问题
301

jQuery怎么动态向页面添加代码?
append() 方法在被选元素的结尾(仍然在内部)插入指定内容。 语法: $(selector).append( content ) var creatPrintList = function(data){ var innerHtml = ""; for(var i =0;i data.length;i++){ innerHtml +="li class='contentLi'"; innerHtml +="a href...
2024-10-18 前端开发问题
125

JavaScript(js)文件字符串中丢失"\"斜线的解决方法
问题描述: 在javascript中引用js代码,然后导致反斜杠丢失,发现字符串中的所有\信息丢失。比如在js中引用input type=text onkeyup=value=value.replace(/[^\d]/g,) ,结果导致正则表达式中的\丢失。 问题原因: 该字符串含有\,javascript对字符串进行了转...
2024-10-17 前端开发问题
437

layui中table列表 增加属性 edit="date",不生效怎么办?
如果你想在 layui 的 table 列表中增加 edit=date 属性但不生效,可能是以下问题导致的: 1. 缺少日期组件的初始化 如果想在表格中使用日期组件,需要在页面中引入 layui 的日期组件,并初始化: script type="text/javascript" src="/layui/layui.js"/scrip...
2024-06-11 前端开发问题
455