I have a custom object that has an attached (png) image to it. I'm trying to create a lightning component that pulls the attachment and draws it on a html canvas. So far in the below code, I'm able to get the img tag to show the attachment. However I cannot find a way for my helper/controller to grab that image and actually draw it on the canvas. How could I accomplish this?


<aura:component controller="ScreenshotEditorComponentController" implements="flexipage:availableForAllPageTypes, force:hasRecordId" access="global">
    <aura:handler name="init" action="{!c.init}" value="{!this}" />

    <aura:attribute name="recordId" type="Id" />
    <aura:attribute name="screenshot" type="Attachment" />

    <canvas aura:id="canvas" id="canvas" width="500" height="500"></canvas>

    <img aura:id="img" src="{!'/servlet/servlet.FileDownload?file=' + v.screenshot.Id}" onload="{c.test}"/>



    init: function(component, event, helper) {
        helper.getData(component, component.get('v.recordId'));


getData: function(component, recordId) {        
    var action = component.get('c.getScreenshotData');
        screenshotId: recordId

    action.setCallback(this, function(response) {
        var state = response.getState();
        if (component.isValid() && state === 'SUCCESS') {
             component.set('v.screenshot', response.getReturnValue());


1 Answer 1


Create renderer file in lighting component and put below code. This will draw image when image data is returned from apex call and set in img src attribute.

        afterRender :  function(cmp){
            var canvas = cmp.find("canvas").getElement();
            //var img = cmp.find("img").getElement();
            var ctx = canvas.getContext('2d');
            var image = new Image();
            //Change ID based on record or uncomment below line 
            //image.src = img.src;
            image.src =  "/servlet/servlet.FileDownload?file=00P7F0000026XRxUAM";
            image.onload = $A.getCallback(function() {
                    ctx.drawImage(image, 0, 0, 200, 300)
  • I got this to work using either of the image.src options you gave, however it is not a 100% success rate. If I keep refreshing the screen, it will draw to the canvas several times in a row, then it will fail to draw several refreshes in a row, with no error. Any ideas?
    – Will
    May 12, 2019 at 23:15
  • Further investigation gave me this: under var canvas = cmp.find(...), I do a var screenshot = cmd.get('v.screenshot'); When it fails to draw, get() is returning null. I require this get, because on the image.src line I use it: image.src = "/servlet/servlet.FileDownload?file=" + screenshot.Id;
    – Will
    May 12, 2019 at 23:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .