Search code examples
javascriptc#winformshtml5-canvas

is there a equivalent to drawing on a bitmap in js


in C# you can create bitmaps, draw on them, and then you can draw those cached bitmaps.

public Form1()
{
    InitializeComponent();
    surface = new Bitmap(640, 480);
    var g = Graphics.FromImage(surface);
    g.DrawRectangle(Pens.Red, 10, 10, 10, 10);
}
Bitmap surface;

private void Form1_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.DrawImage(surface, 0, 0);
}

is there a way to do that in javascript?

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(95,50,40,0,2*Math.PI);
ctx.stroke();
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML canvas tag.</canvas>


Solution

  • Canvas is a drawable image.

    The function's CanvasRenderingContext2D.drawImage() first argument is an image or more specifically a CanvasImageSource which includes the HTMLCanvasElement.

    Example

    Example draws an arc on can1 then draws can1 on can2 using drawImage.

    Note it draw the pixels, the path is not redrawn on the second canvas.

    Note The canvas is "double buffered" which means you can also draw the canvas to itself

    var ctx1 = can1.getContext("2d");
    var ctx2 = can2.getContext("2d");
    ctx1.beginPath();
    ctx1.arc(64, 64, 60, 0, 2 * Math.PI);
    ctx1.stroke();
    
    ctx2.drawImage(can1, 0, 0);
    canvas { border: 1px solid black}
    <canvas id="can1" width="128" height="128"></canvas>
    <canvas id="can2" width="128" height="128"></canvas>