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>
CodePudding user response:
You can cache that drawing as png or jpeg base64 string and then you can put it to any image tag or other canvas as well. Here I have cached that image in png data and drawn on an image tag below:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(95,50,40,0,2*Math.PI);
ctx.stroke();
var dt = c.toDataURL('image/png');
CANVAS_DATA.src = dt;
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML canvas tag.</canvas>
<img id="CANVAS_DATA">
If you need more info please ask.
CodePudding user response:
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>