[]
DsImageViewer provides viewer.setImageDataUrl method to modify the current image URL to the canvas image. To draw an image from scratch, you can use viewer.newImage method which creates an empty image.
async function loadImageViewer() {
// initialize image viewer
var viewer = new DsImageViewer("#imageviewer");
const myCanvas = document.createElement("canvas");
myCanvas.width = 300;
myCanvas.height = 300;
function drawCircle(ctx, centerX, centerY, radius) {
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
ctx.fillStyle = 'green';
ctx.fill();
ctx.lineWidth = 15;
ctx.strokeStyle = '#ff3300';
ctx.stroke();
};
drawCircle(myCanvas.getContext("2d"), 150, 150, 25);
await viewer.newImage({ width: 300, height: 300, fileName: "myImage.png" });
await viewer.setImageDataUrl(myCanvas.toDataURL());
// after drawing new image, download it
viewer.download("paintedimage.png");
}
Similarly, to draw on top of a static image, you can draw the canvas on top of existing image and then call the setImageDataUrl method.
async function loadImageViewer() {
var viewer = new DsImageViewer("#imageviewer");
// zoom out the image
viewer.zoom = { mode: 2 };
// open existing image
await viewer.open("https://i.imgur.com/EUcri31.jpeg");
const naturalSize = viewer.naturalSize;
const canvas = document.createElement("canvas");
canvas.width = naturalSize.width;
canvas.height = naturalSize.height;
const image = new Image;
image.onload = function () {
var ctx = canvas.getContext("2d")
ctx.drawImage(image, 0, 0);
// Paint over existing image
ctx.globalAlpha = 0.3;
ctx.fillStyle = '#00FFFF';
ctx.fillRect(0, 0, naturalSize.width, naturalSize.height / 2);
ctx.globalAlpha = 1.0;
const canvasDataUrl = canvas.toDataURL();
// Set image data
viewer.setImageDataUrl(canvasDataUrl);
// After drawing on top of image, download it
viewer.download("drawonimage.png");
};
image.crossOrigin = "Anonymous";
image.src = viewer.getOriginalImageDataUrl();
}
Note: The DsImageViewer does not support modification of multi-frame images such as .gif, .ico, .tiff, .svg files etc.