Jump to content

Tw3Image, Tw3Canvas, copying any part of image to another Image

Recommended Posts

The normal HTML images (such as <img>) do not have (/ need) a canvas. However, you can draw any image to any canvas. This said, drawing an image to another image is slightly more complicated. For this reason I'd like to focus on the simple case of drawing an image to a canvas.


The below code uses only the underlying W3C API. It should be simple to translate it to higher level SmartCL code.


uses W3C.HTML5, W3C.GraphicContext;

// first get your image handle (replace this line with your image handle such as Image1.handle
var ImageHandle := Document.createElement('image');

// now create a temporary canvas (or replace it with your target canvas)
var TempCanvas := JHTMLCanvasElement(Document.createElement('canvas'));

// eventually adapt the size of the canvas (if not done elsewhere)
TempCanvas.width := ImageHandle.width;
TempCanvas.height := ImageHandle.height;

// for the next step we need the 2d drawing context for this canvas
var Context := JCanvasRenderingContext2D(TempCanvas.getContext('2d'));

// finally you can draw your image on the 2d context of the temporary canvas
Context.drawImage(ImageHandle, 0, 0);
Once you have the image drawn on the canvas you can use this canvas as an image itself.


If you want to load content of the canvas as an image you have to convert it to a data URL first. This can be done with:


var CanvData := TempCanvas.toDataURL('image/png');
This string can then be passed to the 'source' or 'src' field of any image.


If you need the raw image data (pixels) of the image you can write something like the below:


// get image data
var ImageData := Context.getImageData(0, 0, TempCanvas.Width, TempCanvas.Height);
This object contains a field 'data' which is an array of all the pixels (bytes).


In case you need to copy only a small rectangle of the source image to the destination canvas (image), you can change the line


Context.drawImage(ImageHandle, 0, 0);
to something like:


Context.drawImage(ImageHandle, sx, sy, sw, sh, dx, dy, dw, dh);
with sx and sy being the source position to copy from, sw and sh the source width and height and dx, dy the destination position and dw, dh the destination width and height.



As mentioned it can also done with higher level code, but the low level code is already pretty simple and easy to understand, I think. Also, it hopefully helps to get some more background information about HTML5. There are plenty of good resources available if you want to know more, such as http://www.w3schools.com/tags/ref_canvas.asp

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now